<?php

namespace plugins\goods\controller;

use cmf\controller\ApiPluginBaseController;
use plugins\goods\model\GoodsSimilarModel;
use think\Request;
use think\Db;
use think\Paginator\driver\Bootstrap;

class ApiGoodsSimilarController extends ApiPluginBaseController
{

    /**
     * 相似商品
     * @param goods_name 商品名称
     */    
    public function similarGoods()
    {

        $param = $this->request->post();
        if( empty($param['goods_name']) ) return api_json_echo(false,'未获取参数','',100);
        $goods_name = $param['goods_name'];
        $goods = db('goods')->select();
        $model = new GoodsSimilarModel;
        $res = [];
        $goodsid = [];
        foreach( $goods as $key => $value )
        {
            if(count($goodsid) == 70)break;
            //获取相似度值
            $similar = $model->getSimilar ($goods_name,$value['goods_name']);
            //判断相似度
            if($similar >= 0.50){
                $similar = 1- $similar;//倒序
                $res["$similar"] = $value; 
                $goodsid[] = $value['id'];
            }
        }

        $newArrivals = $this->newArrivals();
        foreach( $newArrivals as $key => $val)
        {   
            if(!in_array($val['id'],$goodsid)) $res[$key] = $val;
        }
        
        return api_json_echo(true,'相似商品',$res,200);
    }



    /**
     * 新品推荐
     */
    public function newArrivals()
    {        

        $res = [];
        $store = [];
        $key = 1;
        $list = Db::name('goods')->order('add_time','desc')->select();
        foreach( $list as $value )
        {
            if(count($store) == 20)break;
            if(!in_array($value['store_id'],$store))
            {
                $store[] = $value['store_id'];
                $res[$key] = $value;
                $key++;
            }
        }
        return $res;
    }

     
}

